﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using ExcelCOM = Microsoft.Office.Interop.Excel;
using System.Runtime;

namespace DataAccess
{
    public class SaveListviewToExcel
    {
        private ListView lv;
        public ListView Lv
        {
            get { return lv; }
            set { lv = value; }
        }

        private string pard;
        public string Pard
        {
            get { return pard; }
            set { pard = value; }
        }

        public SaveListviewToExcel() { }

        public SaveListviewToExcel(ListView l, string p)
        {
            Lv = l;
            Pard = p;
        }

        public SaveListviewToExcel(SaveListviewToExcel save)
        {
            Lv = save.Lv;
            Pard = save.Pard;
        }

        public static int Export2Excel(ListView root, string Path,string name)
        {
            int kq = 0;
            int row = 1;

            ExcelCOM.Application exApp = new ExcelCOM.Application();
            ExcelCOM.Workbook exBook = exApp.Workbooks.Add(ExcelCOM.XlWBATemplate.xlWBATWorksheet);
            ExcelCOM.Worksheet exSheet = (ExcelCOM.Worksheet)exBook.Worksheets[1];

            //dat ten cho worksheet
            exSheet.Name = "example sheet";

            for (int i = 0; i < root.Columns.Count; i++)
            {
                exSheet.Cells[1, (i + 1)] = root.Columns[i].Text;
            }

            for (int col = 0; col < root.Items.Count; col++)
            {
                row++;
                for (int k = 0; k < root.Items[col].SubItems.Count; k++)
                {
                    exSheet.Cells[row, (k + 1)] = root.Items[col].SubItems[k].Text;

                }
            }
            if (Path == "")
            {
                Path = "C:\\" + name; //dat duong dan
            }
            exApp.Visible = false;
            try
            {
                exBook.SaveAs(Path, ExcelCOM.XlFileFormat.xlWorkbookNormal, null, null, false, false, ExcelCOM.XlSaveAsAccessMode.xlExclusive, false, false, false, false, false);
                exBook.Close(false, false, false);
                exApp.Quit();
                kq = 1;
            }
            catch
            {
                kq = 0;
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
            return kq;
        }
    }
}
